package com.atguigu.tingshu.account.service.impl;

import com.atguigu.tingshu.account.mapper.RechargeInfoMapper;
import com.atguigu.tingshu.account.mapper.UserAccountDetailMapper;
import com.atguigu.tingshu.account.service.RechargeInfoService;
import com.atguigu.tingshu.account.service.UserAccountService;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.utils.ThrowUtil;
import com.atguigu.tingshu.model.account.RechargeInfo;
import com.atguigu.tingshu.model.account.UserAccountDetail;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Slf4j
@Service
@SuppressWarnings({ "all" })
public class RechargeInfoServiceImpl extends ServiceImpl<RechargeInfoMapper, RechargeInfo>
        implements RechargeInfoService {

    @Autowired
    private RechargeInfoMapper rechargeInfoMapper;

    @Autowired
    private UserAccountDetailMapper userAccountDetailMapper;

    @Autowired
    private UserAccountService userAccountService;

    @Override
    // TODO 分布式事务需要删除
    @Transactional(rollbackFor = Exception.class)
    public void rechargePaySuccess(String orderNo) {
        log.info("在线付款成功后-更新充值状态&账户余额及新增账户变动日志 - orderNo: {}", orderNo);
        // 1. 查询充值订单
        LambdaQueryWrapper<RechargeInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(RechargeInfo::getOrderNo, orderNo);
        RechargeInfo rechargeInfo = rechargeInfoMapper.selectOne(queryWrapper);
        ThrowUtil.throwIf(rechargeInfo == null, "充值订单不存在");
        // 2. 检查订单状态，防止重复处理
        if (SystemConstant.ORDER_STATUS_PAID.equals(rechargeInfo.getRechargeStatus())
                || SystemConstant.ORDER_STATUS_CANCEL.equals(rechargeInfo.getRechargeStatus())) {
            log.warn("充值订单已处理或已取消，跳过 - orderNo: {}", orderNo);
            return;
        }
        // 3. 记录账户明细
        userAccountDetailMapper.saveUserAccountDetail(
                rechargeInfo.getUserId(),
                "在线付款成功后-更新充值状态&账户余额及新增账户变动日志",
                SystemConstant.ACCOUNT_TRADE_TYPE_DEPOSIT,
                rechargeInfo.getRechargeAmount(),
                orderNo);
        log.info("充值成功回调完成 - orderNo: {}", orderNo);
    }
}
